package com.jprocms.module.cms.inteceptor;

import com.jprocms.module.cms.dal.dataobject.site.SiteDO;
import com.jprocms.module.cms.service.site.SiteService;
import com.jprocms.module.cms.util.CmsContextUtil;
import com.jprocms.module.cms.util.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.jpro.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.jprocms.module.cms.enums.ErrorCodeConstants.SITE_NOT_FIND;

/**
 * @author jprocms
 */
@Slf4j
@Component
public class
SiteContextInteceptor implements HandlerInterceptor {
    @Resource
    @Lazy
    private SiteService siteService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj)
            throws Exception {
        SiteDO site = CmsContextUtil.getCurrentSite(siteQueryDto -> siteService.getCurrentSite(siteQueryDto, request));
        if (site == null) {
            log.error("未找到站点");
            throw exception(SITE_NOT_FIND);
        }
        CmsContextUtil.setSite(site);
        return true;
    }


    @Override
    public void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object o, Exception e)
            throws Exception {
        CmsContextUtil.resetSite();
    }
}
